#!/usr/bin/env bash
set -eo pipefail

if [[ -f /etc/environment_proxy ]]; then
	source /etc/environment_proxy
fi

## Load slug from Bind Mount, URL or STDIN

export HOME=/app
mkdir -p $HOME

if [[ $(ls -A $HOME) ]]; then
	true
elif [[ $SLUG_URL ]]; then
	curl -s "$SLUG_URL" | tar -xzC $HOME
	unset SLUG_URL
else
	cat | tar -xzC $HOME
fi

cd $HOME

## Load profile.d and release config

shopt -s nullglob
mkdir -p .profile.d

# If a file is created in slugbuilder with the wrong UID, change it. But we
# don't mess with anything owned by UID 0.
find . -user 1000 -exec chown slug:slug {} \;

if [[ -s .release ]]; then
	ruby -e "require 'yaml';(YAML.load_file('.release')['config_vars'] || {}).each{|k,v| puts \"#{k}='#{v}'\"}" > .profile.d/config_vars
fi
for file in .profile.d/*; do
	source $file
done
hash -r

## Inject "start" command to run processes defined in Procfile

case "$1" in
	start)
		if [[ -f Procfile ]]; then
			command="$(ruby -e "require 'yaml';puts YAML.load_file('Procfile')['$2']")"
		else
			command="$(ruby -e "require 'yaml';puts (YAML.load_file('.release')['default_process_types'] || {})['$2']")"
		fi
		;;

	*)
		command="$@"
		;;
esac

## Use sdutil to register with service discovery

if [[ $SD_NAME && $PORT ]]; then
	if [[ $SD_HOST ]]; then
		runner="sdutil exec -h $SD_HOST -s $SD_NAME:$PORT bash -c"
		unset SD_HOST
	else
		runner="sdutil exec -s $SD_NAME:$PORT bash -c"
	fi
	unset SD_NAME
elif [[ $SD_ARGS ]]; then
	runner="sdutil $SD_ARGS bash -c"
	unset SD_ARGS
else
	runner="bash -c"
fi

## Run!

exec $runner "$command"
